package com.tx.servlet;

import com.tx.dao.ManagerDao;
import com.tx.entity.Manager;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

public class ManagerServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String flag = request.getParameter("flag");
        ManagerDao md = new ManagerDao();
        if ("login".equals(flag)) {
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            try {
                Manager manager = md.login(username, password);
                if (manager == null) {
                    response.sendRedirect("login.html");
                } else {
                    response.sendRedirect("index.jsp");
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }else if ("regist".equals(flag)){
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            int rows = md.regist(username,password);
            PrintWriter out = response.getWriter();
            if (rows==0){
                out.print("<script>alert('不好意思，注册失败');</script>");
                out.close();
            }else {
                response.sendRedirect("login.html");
            }

        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
